package com.shenma2009.controller;

import com.shenma2009.domain.ResultResponse;
import com.shenma2009.service.TbOrderService;
import com.shenma2009.utils.AlipayPayUtils;
import com.shenma2009.utils.QRCodeUtil;
import com.shenma2009.utils.WeixinPayUtils;
import com.shenma2009.vo.WeixinPayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;

/**
 * @author 军哥
 * @version 1.0
 * @description: WeixinPayController
 * @date 2023/4/28 14:42
 */

@RestController
@Slf4j
@RequestMapping(value = "/alipay")
public class AlipayPayController {

    @Autowired
    TbOrderService tbOrderService;

    @PostMapping(value = "/getOrderNo")
    public ResultResponse getOrderNo() throws IOException, URISyntaxException {

        AlipayPayUtils alipayPayUtils = new AlipayPayUtils();
        String orderNo = alipayPayUtils.getOrderNo();

        return ResultResponse.SUCCESS(orderNo);
    }

    @PostMapping(value = "/getOrderState/{orderId}")
    public ResultResponse getOrderState(@PathVariable("orderId") String orderId) throws IOException, URISyntaxException {

        AlipayPayUtils alipayPayUtils = new AlipayPayUtils();
        Integer orderState = alipayPayUtils.getOrderState(orderId);

        // 未支付
        if(orderState.equals(0)) {
            return ResultResponse.FAILED(201, "订单未支付");
        }
        // 支付成功
        else if(orderState.equals(1)) {
            return ResultResponse.FAILED(200, "支付成功");
        }

        return ResultResponse.FAILED(500, "获取支付状态失败");
    }

    @PostMapping(value = "/postOrderPay")
    public ResultResponse postOrderPay(@RequestBody WeixinPayVo weixinPayVo) {
        AlipayPayUtils alipayPayUtils = new AlipayPayUtils();
        String url_code = alipayPayUtils.postOrderPay(weixinPayVo.getOrderId(), weixinPayVo.getAmount(), weixinPayVo.getDesc());

        return ResultResponse.SUCCESS(url_code);
    }

    @GetMapping(value = "/getOrderQRCode/{orderNo}/{amount}")
    public void getOrderQRCode(HttpServletResponse response, @PathVariable("orderNo") String orderNo, @PathVariable("amount") Integer amount) {
        AlipayPayUtils alipayPayUtils = new AlipayPayUtils();
        String codeUrl = alipayPayUtils.postOrderPay(orderNo, amount, "支付测试");
        if(codeUrl != null) {
            QRCodeUtil.createQRCode(response, codeUrl);
        }
    }

    @GetMapping(value = "/payOrderOK/{orderId}/{orderNo}")
    public ResultResponse payOrderOK(@PathVariable("orderId") Integer orderId, @PathVariable("orderNo") String orderNo) {
        return tbOrderService.payOrderOK(orderId, orderNo);
    }

}
